//
// Created by guanzhe on 15/12/28.
// Copyright (c) 2015 MengHuan. All rights reserved.
// 信息管理
//

#import "MsgVc.h"
#import "BaseTableView.h"
#import "UIViewController+common.h"
#import "UIColor+Extension.h"
#import "MJRefreshNormalHeader.h"
#import "MJRefreshFooter.h"
#import "Usermodel.h"
#import "Macro.h"
#import "MsgCell.h"
#import "CommonSearchBar.h"
#import "MsgEditVc.h"
#import "DataModel.h"

static const NSString *cellIdentifier = @"MsgCell";

@interface MsgVc () <UITableViewDelegate, UITableViewDataSource,UISearchBarDelegate,CommonClickDelegate,UIAlertViewDelegate> {
    NSMutableArray *_tableDataArr;
    NSString *_title;//搜索用的title 一开始为空
    UIAlertView *_deleteAlertView;
    MsgModel *_deleteModel;
    CommonModel *_commonModel;

}
@property (weak, nonatomic) IBOutlet CommonSearchBar *searchBar;
@property(weak, nonatomic) IBOutlet BaseTableView *tableView;
@property(nonatomic, assign) int page;//某些请求数据有页码的页面用到的参数

@end

@implementation MsgVc {

}

- (void)viewDidLoad {
    [super viewDidLoad];
    NAV_INIT(self, @"信息列表", @"back", @selector(backButtonClick:), @"添加", @selector(rightBtnClick));
    [self initTab];
    self.searchBar.delegate = self;
    self.searchBar.placeholder = @"消息标题";
    _deleteAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确认要删除此信息吗" delegate:self
            cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil ];
    [_deleteAlertView dismissWithClickedButtonIndex:0 animated:YES];
    [_deleteAlertView dismissWithClickedButtonIndex:1 animated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.page = 1;
    _title = @"";//置空
    [self.tableView.header beginRefreshing];
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}


- (void)rightBtnClick {
    if(_commonModel == nil){
        return;
    }
    if(_commonModel.addFlag.description.intValue != 1){
        [SVProgressHUD showErrorWithStatus:@"您无权限执行此操作"];
        return;
    }
    MsgEditVc * msgEditVc = kHome_storyVCName(@"MsgEditVc");
    msgEditVc.type = MSG_NEW_TYPE;
    [self.navigationController pushViewController:msgEditVc animated:YES];
}

- (void)initTab {
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor backgroundColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.tableFooterView.backgroundColor = [UIColor backgroundColor];
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        self.page = 1;
        _title = @"";//置空
        [self requestList];
    }];
    [self.tableView addFooterRefreshTarget:self action:@selector(requestLoadMoreDataByPage)];
}

//alert delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        [UserServices deleteMsgByToken:[[AppDelegate appDelegate] getUserInfo].token
                                 msgId:_deleteModel.id
                       completionBlock:^(int result, id responseObject) {
                           [_tableDataArr removeObject:_deleteModel];
                           [self.tableView reloadData];
                       }];
    }
}

#pragma mark - UISearchBarDelegate

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    [searchBar setShowsCancelButton:YES animated:YES];
    [self.searchBar setCancelButtonTitle:@"取消"];
    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
    return YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    _title = self.searchBar.text;
    self.page = 1;
    [self requestList];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    searchBar.text = @"";
    [searchBar resignFirstResponder];
    [searchBar setShowsCancelButton:NO animated:YES];
}

#pragma click

- (void)clickActionWithData:(JSONModel *)data AndType:(NSString *)type {
    MsgModel *msgModel = (MsgModel *)data;
    if([@"repair" isEqualToString:type]){
        if(_commonModel.modFlag.description.intValue != 1){
            [SVProgressHUD showErrorWithStatus:@"您无权限执行此操作"];
            return;
        }
        MsgEditVc * msgEditVc = kHome_storyVCName(@"MsgEditVc");
        msgEditVc.type = MSG_EDIT_TYPE;
        msgEditVc.msgTitle = msgModel.title;
        msgEditVc.msgContent = msgModel.message;
        msgEditVc.msgId = msgModel.id;
        msgEditVc.model = msgModel;
        [self.navigationController pushViewController:msgEditVc animated:YES];
    }else{
        if(_commonModel.delFlag.description.intValue != 1){
            [SVProgressHUD showErrorWithStatus:@"您无权限执行此操作"];
            return;
        }
        _deleteModel = msgModel;
        [_deleteAlertView show];
    }

}


#pragma mark 返回分组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


#pragma mark head的高度

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0;
}

#pragma mark 返回每组行数

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _tableDataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 168;
}

#pragma mark返回每行的单元格

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MsgCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell)
        cell = [[[UINib nibWithNibName:cellIdentifier bundle:nil] instantiateWithOwner:self options:nil] lastObject];
    [cell setCellInfo:_tableDataArr andPosition:indexPath.row];
    cell.delegate = self;
    return cell;
}

#pragma mark 底部刷新
- (void)requestLoadMoreDataByPage {
    self.page++;
    [self requestList];
}

#pragma mark 请求数据

- (void)requestList {
    [UserServices getMsgListByToken:[[AppDelegate appDelegate] getUserInfo].token
                              title:_title
                               page:kIntToString(self.page)
                           pagesize:kIntToString(kListPageSize)
                    completionBlock:^(int result, id responseObject) {
                        _commonModel = responseObject;
                        if (result == API_Request_Success) {
                            NSMutableArray *array = _commonModel.messagePage;
                            if (self.page == API_Request_Success) {
                                _tableDataArr = array;
                                [self.tableView.footer resetNoMoreData];//重置有更多数据
                                if (array == nil || array.count == 0) {
                                    //提示无数据
                                    [SVProgressHUD showErrorWithStatus:@"查无数据"];
                                } else {
                                }
                            }
                            else
                                [_tableDataArr addObjectsFromArray:array];
                            if (array.count == 0) {
                                self.page--;
                            }
                            [self.tableView.header endRefreshing];
                            [self.tableView.footer endRefreshing];
                            [self.tableView reloadData];
                            if (array.count < kListPageSize)
                                [self.tableView.footer noticeNoMoreData];//没有更多数据
                        } else {//出错时的处理
                            //提示出错
                            [SVProgressHUD showErrorWithStatus:Error_Format];
                        }
                    }];
}

@end